//获取url中的参数
function get_url_parm() {
    var qs = location.search.substr(1), // 获取url中"?"符后的字串
        args = {}, // 保存参数数据的对象
        items = qs.length ? qs.split("&") : [], // 取得每一个参数项,
        item = null,
        len = items.length;

    for (var i = 0; i < len; i++) {
        item = items[i].split("=");
        var name = decodeURIComponent(item[0]),
            value = decodeURIComponent(item[1]);
        if (name) {
            args[name] = value;
        }
    }
    return args;
}

/**
 * 创建cookies
 * createCookie("_fv", "1", 30, "/;domain=abc.com")
 */

function create_cookie(name, value, expire, path) {
    var d = path ? path : "/";
    if (expire) {
        var e = new Date;
        e.setTime(e.getTime() + 1e3 * 60 * 60 * 24 * expire);
        var f = "; expires=" + e.toGMTString()
    } else var f = "";
    document.cookie = name + "=" + value + f + "; path=" + d
}

/**
 * 读取cookies
 * @param a
 * @returns {*}
 */
function read_cookie(a) {
    for (var b = a + "=", c = document.cookie.split(";"), d = 0; d < c.length; d++) {
        for (var e = c[d];
             " " == e.charAt(0);) e = e.substring(1, e.length);
        if (0 == e.indexOf(b)) return e.substring(b.length, e.length)
    }
    return null
}

/**
 * //为了删除指定名称的cookie
 * @param name
 */
function del_cookie(name) {
    var date = new Date();
    date.setTime(date.getTime() - 10000);
    document.cookie = name + "=a; expires=" + date.toGMTString();
}

/**
 * 判断是否null
 * @param data
 */
function is_null(data) {
    return (data == "" || data == undefined || data == null) ? true : false;
}

/*
判断是否为数字
 */
function check_is_num(input) {
    if (is_null(input))
        return false;
    var re = /^[0-9]+.?[0-9]*$/;   //判断字符串是否为数字     //判断正整数 /^[1-9]+[0-9]*]*$/
    return re.test(input)
}

/**
 * //获取当前时间
 * @param name
 */
function current() {
    return (new Date()).Format("yyyy-MM-dd hh:mm:ss");
}

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

/*
 将文本转换成时间
 */
function str2date(str) {
    var d = null;
    var reg = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\.(\d+)$/
    if (arr = str.match(reg)) d = new Date(Number(arr[1]), Number(arr[2]) - 1, Number(arr[3]), Number(arr[4]), Number(arr[5]), Number(arr[6]), Number(arr[7]))
    return d;
}

/*
 将时间转换成文本
 */
function date2str(d) {
    var ret = d.getFullYear() + "-";
    ret += ("00" + (d.getMonth() + 1)).slice(-2) + "-";
    ret += ("00" + d.getDate()).slice(-2) + " ";
    ret += ("00" + d.getHours()).slice(-2) + ":";
    ret += ("00" + d.getMinutes()).slice(-2) + ":";
    ret += ("00" + d.getSeconds()).slice(-2);
    return ret;
}

/*
 将时间戳转换成文本
 */
function unixtime2str(timestamp) {
    if (is_null(timestamp)) {
        return "";
    }
    else if (!is_number(timestamp)) {
        return timestamp;
    } else {
        var d = new Date(parseInt(timestamp) * 1000);
        return date2str(d);
    }
}

function unixtime2str_date(timestamp) {
    if (is_null(timestamp)) {
        return "";
    }
    else if (!is_number(timestamp)) {
        return timestamp;
    } else {
        var d = new Date(parseInt(timestamp) * 1000);
        return date3str(d);
    }
}

/*
 将时间转换成文本
 */
function date3str(d) {
    var ret = d.getFullYear() + "-";
    ret += ("00" + (d.getMonth() + 1)).slice(-2) + "-";
    ret += ("00" + d.getDate()).slice(-2) + " ";
    return ret;
}

/**
 * var t =  parseInt(时间戳*1000);
 * new Date(t).format('yyyy-MM-dd');
 * 将时间戳按指定格式 格式化
 * @param format
 * @returns {*}
 */
Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(), //day
        "h+": this.getHours(), //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
        "S": this.getMilliseconds() //millisecond
    };
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
        (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) if (new RegExp("(" + k + ")").test(format))
        format = format.replace(RegExp.$1,
            RegExp.$1.length == 1 ? o[k] :
                ("00" + o[k]).substr(("" + o[k]).length));
    return format;
};

/**
 * 生成一个编辑器
 */

function create_editor(textarea_id) {
    if (textarea_id && !document.getElementById(textarea_id)) {
        alert("代码错误:" + textarea_id + "不存在");
    }
    var editor = KindEditor.create('#' + textarea_id, {
            allowFileManager: false,
            uploadJson: '/public/upload/epic',
            afterCreate: function () { //kindeditor创建后，将编辑器的内容设置到原来的textarea控件里
                this.sync();
            },

            afterChange: function () { //编辑器内容发生变化后，将编辑器的内容设置到原来的textarea控件里
                this.sync();
            },
            afterBlur: function () { //编辑器聚焦后，将编辑器的内容设置到原来的textarea控件里
                this.sync();
            }
}
    );
    return editor;
}

/**
 * 生成一个编辑器
 */

function create_simaple_editor(textarea_id) {
    if (textarea_id && !document.getElementById(textarea_id)) {
        alert("代码错误:" + textarea_id + "不存在");
    }
    var editor = KindEditor.create('#' + textarea_id, {
            allowFileManager: false,
            uploadJson: '/public/upload/epic',
            afterCreate: function () { //kindeditor创建后，将编辑器的内容设置到原来的textarea控件里
                this.sync();
            },

            afterChange: function () { //编辑器内容发生变化后，将编辑器的内容设置到原来的textarea控件里
                this.sync();
            },
            afterBlur: function () { //编辑器聚焦后，将编辑器的内容设置到原来的textarea控件里
                this.sync();
            },
            items : [
                'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
                'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
                'insertunorderedlist', '|', 'emoticons', 'image', 'link']
        }
    );
    return editor;
}

//判断函数是否存在
function is_exists_function(funcName) {
    try {
        if (typeof(eval(funcName)) == "function") {
            return true;
        }
    } catch (e) {
    }
    return false;
}

/*
表单提交
 */
function post_data(action, data, is_close, success_callback, failure_callback, is_tip) {
    $ = layui.$;
    var parent_layer_index = parent.layer.getFrameIndex(window.name);//获取窗口索引
    var loading = show_progress('正在处理中...');
    $.ajax({
        url: action
        , type: 'post'
        , data: data
        , async: true
        , dataType: 'json'
        , success: function (res) {//这里要说明一下：done 是只有 response 的 code 正常才会执行。而 succese 则是只要 http 为 200 就会执行
            console.log(res);

            if (res.status == 200) {
                ////================== 正确处理==================
                if (success_callback !== undefined || success_callback !== "") {
                    try {
                        success_callback(res);
                    } catch (e) {
                        console.log(e);
                    }
                }
                //是否提示
                if (is_tip === undefined || is_tip == 1) {
                    //================== 错误提示区 ==================
                    show_success(res.message);
                }

                //================== 父窗口操作区 ==================
                //如果是iframe子页面，就关闭上级页面的本窗口
                if ((is_close === undefined || is_close == 1) && !is_null(parent_layer_index)) {
                    parent.layer.close(parent_layer_index);
                }
            } else {
                ////================== 错误处理==================
                if (failure_callback !== undefined || failure_callback !== "") {
                    try {
                        failure_callback(res);
                    } catch (e) {
                        console.log(e);
                    }
                }
                //是否提示
                if (is_tip === undefined || is_tip == 1) {
                    //================== 错误提示区 ==================
                    show_error(res.message);
                }
            }

        }, error: function () {
            show_error('网络异常');
        }, done: function () {
            //关闭loadding层
            layer.close(loading);
        }
    });
}

/**
 * 把form下的字段转化成json
 * @param frm
 * @returns {{}}
 */
function form_data_to_json(form_id) {
    if (form_id && !document.getElementById(form_id)) {
        console.log("form id::" + form_id + "不存在");
        return {};
    }
    $ = layui.$;
    var o = {};
    var a = $("#" + form_id).serializeArray();
    $.each(a, function () {
        if (this.name == 'lid2') {
            var tmp = '#' + form_id + ' select[name="' + this.name + '"]';
            //alert($(tmp).attr('type') == 'checkbox' && $(tmp).attr('lay-skin') == 'switch' && $(tmp).value == 1);
        }

        if (!is_null($('#' + form_id + ' select[name="' + this.name + '"]').attr('xm-select'))) {
            o[this.name] = formSelects.value(this.name, 'val').join(",");
            console.log(o[this.name]);
        } else if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });

    //修正layui在switch值为1时，不选中置为0
    $('#' + form_id + ' input[lay-skin="switch"]').each(function (i) {
        if ($(this).val() == 1 && !($(this).attr('name') in o)) {
            o[$(this).attr('name')] = 0;
        }
    });
    //修正layui在switch值为1时，不选中置为0
    $('#' + form_id + ' input[type="checkbox"]').each(function (i) {
        if ($(this).val() == 1 && !($(this).attr('name') in o)) {
            o[$(this).attr('name')] = 0;
        }
    });

    console.log('form data:');
    console.log(o);

    return o;
}

//判断obj是否为json对象
function is_json(obj) {
    var isjson = typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
    return isjson;
}

function get_jquery() {

}

/*
将json的值传入form
 */
function json_to_form(jsonStr, form_id) {
    $ = layui.$;
    if (form_id && !document.getElementById(form_id)) {
        alert("代码错误:" + form_id + "不存在");
    }
    var obj = jsonStr;
    if (is_json(jsonStr)) {
        obj = jsonStr;
    } else {
        obj = eval("(" + jsonStr + ")");
        //obj = JSON.parse(jsonStr);
    }

    var key, value, tagName, type, arr, input_skin;
    for (x in obj) {
        key = x;
        value = obj[x];

        var xpath;
        if (form_id) {
            xpath = "#" + form_id + " [name='" + key + "'],[name='" + key + "[]']";
        }
        else {
            xpath = "[name='" + key + "'],[name='" + key + "[]']";
        }
        $(xpath).each(function () {
            tagName = $(this)[0].tagName;
            type = $(this).attr('type');
            input_skin = $(this).attr('lay-skin');
            if (tagName == 'INPUT') {
                if (input_skin == 'switch') {
                    if (value == 1 || value == "1") {
                        $(this).attr('checked', 'checked');
                        $(this).prop('checked', 'checked');
                        $(this).val('1');
                    } else {
                        $(this).removeAttr('checked');
                    }
                }
                else if (type == 'radio') {
                    $(this).attr('checked', $(this).val() == value);
                } else if (type == 'checkbox') {
                    if (!is_null(value)) {
                        arr = value.split(',');
                        for (var i = 0; i < arr.length; i++) {
                            if ($(this).val() == arr[i]) {
                                $(this).attr('checked', true);
                                break;
                            }
                        }
                    }
                } else {
                    $(this).val(value);
                }
            } else if (tagName == 'SELECT' || tagName == 'TEXTAREA') {
                if (!is_null(($(this).attr('xm-select')))) {
                    //console.log($(this).attr('name'));
                    if(!is_null(value)){
                        formSelects.value($(this).attr('name'), value.split(','), true);
                    }
                }else{
                    $(this).val(value);
                }
            }
        });
    }
}

/*
 弹出进度条
 */
function msg_progress(time, msg) {
    $ = layui.$;
    if (!is_number(time) || time < 1)
        time = 10 * 1000;
    if (!msg)
        msg = '正在加载中...';
    var win = $.messager.progress({
        title: '提示',
        msg: msg
    });
    setTimeout(function () {
        $.messager.progress('close');
    }, time)
}

//验证字符串是否是数字
function is_number(theObj) {
    var reg = /^[0-9]+.?[0-9]*$/;
    if (reg.test(theObj)) {
        return true;
    }
    return false;
}

//显示提示信息
function show_info(msg, time, icon) {
    if (!is_number(time) || time < 1) time = 1000;
    if (!is_number(icon) || icon < 0) icon = 1;

    return parent.parent.parent.parent.parent.layer.msg(msg, {
        icon: icon
        , offset: '15px'
        , time: time
    });
}

//显示警告
function show_warn(msg) {
    return show_info(msg, 3000, 0);
}

//显示正确
function show_success(msg) {
    return show_info(msg, 3000, 1);
}

//显示错误
function show_error(msg) {
    return show_info(msg, 3000, 2);
}

//显示问号
function show_ask(msg) {
    return show_info(msg, 3000, 3);
}

//显示锁
function show_lock(msg) {
    return show_info(msg, 3000, 4);
}

//显示不开心
function show_unhappy(msg) {
    return show_info(msg, 3000, 5);
}

//显示开心的笑脸
function show_happy(msg) {
    return show_info(msg, 3000, 6);
}

function show_progress(msg) {
    return show_info(msg, 10 * 1000, 16);
}

function show_progress_close() {

}

/**
 * 格式字符串
 * var template1="我是{0}，今年{1}了";
 * var template2="我是{name}，今年{age}了";
 * var result1=template1.format("loogn",22);
 * var result2=template2.format({name:"loogn",age:22});
 * @param args
 * @returns {String}
 */
String.prototype.format = function (args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                if (args[key] != undefined) {
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    var reg = new RegExp("({)" + i + "(})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
};

function openwinx(url, name, w, h) {
    if (!w) w = screen.width - 4;
    if (!h) h = screen.height - 95;
    window.open(url, name, "top=100,left=400,width=" + w + ",height=" + h + ",toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,status=no");
}


function parseUrl(paras, url) {
    var url = arguments[1] ? arguments[1] : location.href;
    var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
    var paraObj = {}
    for (i = 0; j = paraString[i]; i++) {
        paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length);
    }
    var returnValue = paraObj[paras.toLowerCase()];
    if (typeof (returnValue) == "undefined") {
        return "";
    } else {
        return returnValue;
    }
}

//生成链接文本
function html_anchor(url, text, tar, fun) {
    if (!text) {
        text = url;
    }
    if (!tar) {
        tar = '_self';
    }

    var html = '<a href="' + url + '" target="' + tar + '">' + text + '</a>';
    return html;
}

//浏览器跳转
function go(url) {
    if (url) {
        window.location.href = url;
    }
}

Array.prototype.contains = function (needle) {
    for (i in this) {
        if (this[i] == needle) return true;
    }
    return false;
};

function array_out_repeat(a) {
    var hash = [], arr = [];
    for (var i = 0; i < a.length; i++) {
        hash[a[i]] != null;
        if (!hash[a[i]]) {
            arr.push(a[i]);
            hash[a[i]] = true;
        }
    }
    return arr;
}

Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};

function store_tree_close_nodes(tree_id, node_id) {
    var expand_nodes_ids = read_cookie("tree_state_" + tree_id);
    var ids = [];
    if (expand_nodes_ids) {
        ids = expand_nodes_ids.split(',');
    }
    ids.remove(node_id);
    create_cookie("tree_state_" + tree_id, ids)
}

function copy_to_clipboard(txt) {
    if (window.clipboardData) {
        window.clipboardData.clearData();
        window.clipboardData.setData("Text", txt);
        show_msg("已经成功复制到剪帖板上！");
    } else if (navigator.userAgent.indexOf("Opera") != -1) {
        window.location = txt;
    } else if (window.netscape) {
        try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        } catch (e) {
            show_msg("被浏览器拒绝！<br />请在浏览器地址栏输入'about:config'并回车<br />然后将'signed.applets.codebase_principal_support'设置为'true'");
        }
        var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
        if (!clip) return;
        var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
        if (!trans) return;
        trans.addDataFlavor('text/unicode');
        var str = new Object();
        var len = new Object();
        var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
        var copytext = txt;
        str.data = copytext;
        trans.setTransferData("text/unicode", str, copytext.length * 2);
        var clipid = Components.interfaces.nsIClipboard;
        if (!clip) return false;
        clip.setData(trans, null, clipid.kGlobalClipboard);
        show_msg("已经成功复制到剪帖板上！");
    }
}

String.prototype.stripHTML = function () {
    var reTag = /<(?:.|\s)*?>/g;
    return this.replace(reTag, "");
};


/*
*获取当前日期前N天或后N日期(N = day)
*type:1：前；2：后
*/
function GetDate(day, type) {
    var zdate = new Date();
    var edate;
    if (type === 1) {
        edate = new Date(zdate.getTime() - (day * 24 * 60 * 60 * 1000));
    } else {
        edate = new Date(zdate.getTime() + (day * 24 * 60 * 60 * 1000));
    }
    return edate;
}

/*
*获取传入的日期前N天或后N日期(N = day)
*type:1：前；2：后
*date：传入的日期
*/
function GetDate2(day, type, date) {
    var zdate;
    if (date === null || date === undefined) {
        zdate = new Date();
    } else {
        zdate = date;
    }
    var edate;
    if (type === 1) {
        edate = new Date(zdate.getTime() - (day * 24 * 60 * 60 * 1000));
    } else {
        edate = new Date(zdate.getTime() + (day * 24 * 60 * 60 * 1000));
    }
    return edate;
}

/*
*获取今日的起始和结束时间
*返回值："起始时间,结束时间"
*/
function toDayStr() {
    var returnStr = "";
    var date = new Date();      //当前时间
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    month = month < 10 ? "0" + month : month;
    day = day < 10 ? "0" + day : day;
    returnStr = year + "-" + month + "-" + day + " 00:00:00,";       //起始时间
    returnStr += year + "-" + month + "-" + day + " 23:59:59";      //结束时间
    return returnStr;
}

/*
*获取昨日的起始和结束时间
*返回值："起始时间,结束时间"
*/
function yesterDayStr() {
    var date = GetDate(1, 1);       //当前时间前一天
    var returnStr = "";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    month = month < 10 ? "0" + month : month;
    day = day < 10 ? "0" + day : day;
    returnStr = year + "-" + month + "-" + day + " 00:00:00,";       //起始时间
    returnStr += year + "-" + month + "-" + day + " 23:59:59";      //结束时间
    return returnStr;
}

/*
*获取本周的起始和结束时间
*返回值："起始时间,结束时间"
*/
function thisWeekStr() {
    var returnStr = "";
    var date = new Date();      //当前时间
    var week = date.getDay();   //获取今天星期几
    if (week == 0) {
        week = 7;
    }
    var monday = GetDate2(week - 1, 1, date);      //获取星期一
    var sunday = GetDate2(7 - week, 2, date);   //获取星期天
    //起始时间的年月日
    var year1 = monday.getFullYear();
    var month1 = monday.getMonth() + 1;
    var day1 = monday.getDate();
    //结束时间的年月日
    var year2 = sunday.getFullYear();
    var month2 = sunday.getMonth() + 1;
    var day2 = sunday.getDate();
    //处理起始时间小于10的追加"0"在前面
    month1 = month1 < 10 ? "0" + month1 : month1;
    day1 = day1 < 10 ? "0" + day1 : day1;
    //处理结束时间小于10的追加"0"在前面
    month2 = month2 < 10 ? "0" + month2 : month2;
    day2 = day2 < 10 ? "0" + day2 : day2;

    returnStr = year1 + "-" + month1 + "-" + day1 + " 00:00:00,";       //起始时间
    returnStr += year2 + "-" + month2 + "-" + day2 + " 23:59:59";      //结束时间
    return returnStr;
}

/*
*获取上周的起始和结束时间
*返回值："起始时间,结束时间"
*/
function lastWeekStr() {
    var returnStr = "";
    var date = new Date();      //当前时间
    var week = date.getDay();   //获取今天星期几
    if (week == 0) {
        week = 7;
    }
    var monday = GetDate2(week + 6, 1, date);      //获取上周星期一
    var sunday = GetDate2(week, 1, date);          //获取上周星期天
    //起始时间的年月日
    var year1 = monday.getFullYear();
    var month1 = monday.getMonth() + 1;
    var day1 = monday.getDate();
    //结束时间的年月日
    var year2 = sunday.getFullYear();
    var month2 = sunday.getMonth() + 1;
    var day2 = sunday.getDate();
    //处理起始时间小于10的追加"0"在前面
    month1 = month1 < 10 ? "0" + month1 : month1;
    day1 = day1 < 10 ? "0" + day1 : day1;
    //处理结束时间小于10的追加"0"在前面
    month2 = month2 < 10 ? "0" + month2 : month2;
    day2 = day2 < 10 ? "0" + day2 : day2;

    returnStr = year1 + "-" + month1 + "-" + day1 + " 00:00:00,";       //起始时间
    returnStr += year2 + "-" + month2 + "-" + day2 + " 23:59:59";      //结束时间
    return returnStr;
}

/*
*获取本月的起始和结束时间
*返回值："起始时间,结束时间"
*/
function thisMonthStr() {
    var returnStr = "";
    var date = new Date();      //当前时间
    var year = date.getFullYear();
    var month = date.getMonth();

    var min = new Date(year, month, 1);                 //本月月初
    var max = new Date(year, month + 1, 0);             //本月月底

    //起始时间的年月日
    var year1 = min.getFullYear();
    var month1 = min.getMonth() + 1;
    var day1 = min.getDate();
    //结束时间的年月日
    var year2 = max.getFullYear();
    var month2 = max.getMonth() + 1;
    var day2 = max.getDate();
    //处理起始时间小于10的追加"0"在前面
    month1 = month1 < 10 ? "0" + month1 : month1;
    day1 = day1 < 10 ? "0" + day1 : day1;
    //处理结束时间小于10的追加"0"在前面
    month2 = month2 < 10 ? "0" + month2 : month2;
    day2 = day2 < 10 ? "0" + day2 : day2;

    returnStr = year1 + "-" + month1 + "-" + day1 + " 00:00:00,";       //起始时间
    returnStr += year2 + "-" + month2 + "-" + day2 + " 23:59:59";      //结束时间
    return returnStr;
}

/*
*获取上月的起始和结束时间
*返回值："起始时间,结束时间"
*/
function lastMonthStr() {
    var returnStr = "";
    var dayMSec = 24 * 3600 * 1000;
    var today = new Date();      //当前时间
    //得到上一个月的第一天
    var lastMonthFirstDay = new Date(today.getFullYear(), today.getMonth() - 1, 1);
    //得到本月第一天
    var nowMonthFirstDay = new Date(today.getFullYear(), today.getMonth(), 1);
    //得到上一个月的最后一天的毫秒值
    var lastMonthLastDayMSec = nowMonthFirstDay.getTime() - 1 * dayMSec;
    var lastMonthLastDay = new Date(lastMonthLastDayMSec);

    returnStr = lastMonthFirstDay.format('yyyy-MM-dd') + " 00:00:00,";       //起始时间
    returnStr += lastMonthLastDay.format('yyyy-MM-dd') + " 23:59:59";      //结束时间
    return returnStr;
}

//按数字类型排序 自定义排序
function sort_num(a, b) {
    if (parseFloat(a) > parseFloat(b)) return 1;
    else return -1;
}

function form_do_set_day(settype, start_id, end_id) {
    $ = layui.$;
    var res = "";
    if (is_null(start_id))
        start_id = "search_start_date";
    if (is_null(end_id))
        end_id = "search_end_date";
    switch (settype) {
        case 1:
            res = toDayStr();//今日
            break;
        case 2:
            res = yesterDayStr();//昨天
            break;
        case 3:
            res = thisWeekStr();//本周
            break;
        case 4:
            res = lastWeekStr();//上周
            break;
        case 5:
            res = thisMonthStr();//本月
            break;
        case 6:
            res = lastMonthStr();//上月
            break;
        default:
            res = "";
    }

    if (res != "") {
        var strs = res.split(",");
        try {
            if ($('#' + start_id).attr("format") == 'datetime') {
                $('#' + start_id).val(strs[0]);
            } else if ($('#' + start_id).attr("format") == 'date') {
                $('#' + start_id).val(strs[0].substring(0, 10));
            }
            if ($('#' + end_id).attr("format") == 'datetime') {
                $('#' + end_id).val(strs[1]);
            } else if ($('#' + end_id).attr("format") == 'date') {
                $('#' + end_id).val(strs[1].substring(0, 10));
            }
        } catch (e) {
            //
        }
    }
    return false;
}

function show_one_pic(src, thumb, title) {
    if (is_null(thumb)) {
        thumb = '';
    }
    if (is_null(title)) {
        title = '';
    }


    layer.photos({
        photos: {
            "title": title //相册标题
            , "data": [{
                "src": src //原图地址
            }]
        }
        , shade: 0.6
        , closeBtn: 1
        , anim: 5
    });
}

//修正iframe的高度
function fix_iframe() {
    layui.use(['layer'], function (args) {
        try {
            var iframe_index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
            parent.layer.iframeAuto(iframe_index);
        } catch (e) {

        }
    });
}

function show_user_base_detail(uid, username) {
    if (is_null(uid) || uid == 0) {
        return false;
    }
    var show_user_base_detail_url = '/cp/user/cp_user/index_base_detail';
    var index = layer.open({
        type: 2
        , title: '会员画像:' + username
        , content: show_user_base_detail_url + "?uid=" + uid
        , area: ['650px', '500px'] //宽高
        , scrollbar: false
        //, closeBtn: 2
        , shadeClose: true
        , end: function (index, layero) {
            //关闭弹窗后的事件
        }
    });
}

//显示会员画像
function on_show_user_base_detail() {
    layui.use(['table'], function (args) {
        var table = layui.table
        ;

        //监听单元格事件
        table.on('tool()', function (obj) {
            var data = obj.data;
            if (obj.event === 'show_user_base_detail') {

                show_user_base_detail(data.uid, data.username);
            }
        });
    });
}

//弹出新tab
function open_tab(url, title) {
    try {
        var topLayui = parent === self ? layui : top.layui;
        topLayui.index.openTabsPage(url, title);
    } catch (e) {
        window.open(url);
    }
}

//开启|关闭
var layui_table_swith_tpl_1 = function (d) {
    var tpl_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="开启|关闭" checked type="checkbox" lay-skin="switch">';
    var tpl_no_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="开启|关闭" type="checkbox" lay-skin="switch">';
    return d[this.field] == 1 ? tpl_checked : tpl_no_checked;
};


//已处理|待处理
var layui_table_swith_tpl_16 = function (d) {
    var tpl_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="已处理|待处理" checked type="checkbox" lay-skin="switch">';
    var tpl_no_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="已处理|待处理" type="checkbox" lay-skin="switch">';
    return d[this.field] == 1 ? tpl_checked : tpl_no_checked;
};


//上架|下架
var layui_table_swith_tpl_12 = function (d) {
    var tpl_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="上架|下架" checked type="checkbox" lay-skin="switch">';
    var tpl_no_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="上架|下架" type="checkbox" lay-skin="switch">';
    return d[this.field] == 1 ? tpl_checked : tpl_no_checked;
};
//处理|未处理
var layui_table_swith_tpl_22 = function (d) {
    var tpl_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="已处理|未处理" checked type="checkbox" disabled="disabled"  lay-skin="switch">';
    var tpl_no_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="已处理|未处理" type="checkbox" disabled="disabled"  lay-skin="switch">';
    return d[this.field] == 1 ? tpl_checked : tpl_no_checked;
};

//开启|关闭，不能修改
var layui_table_swith_tpl_11 = function (d) {
    var tpl_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="开启|关闭" checked type="checkbox" lay-skin="switch" disabled>';
    var tpl_no_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="开启|关闭" type="checkbox" lay-skin="switch" disabled>';
    return d[this.field] == 1 ? tpl_checked : tpl_no_checked;
};

//是|否
var layui_table_swith_tpl_2 = function (d) {
    var tpl_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="是|否" checked type="checkbox" lay-skin="switch">';
    var tpl_no_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="是|否" type="checkbox" lay-skin="switch">';
    return d[this.field] == 1 ? tpl_checked : tpl_no_checked;
};

//显示|关闭
var layui_table_swith_tpl_3 = function (d) {
    var tpl_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="显示|关闭" checked type="checkbox" lay-skin="switch">';
    var tpl_no_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="显示|关闭" type="checkbox" lay-skin="switch">';
    return d[this.field] == 1 ? tpl_checked : tpl_no_checked;
};

//启用|禁用
var layui_table_swith_tpl_4 = function (d) {
    var tpl_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="启用|禁用" checked type="checkbox" lay-skin="switch">';
    var tpl_no_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="启用|禁用" type="checkbox" lay-skin="switch">';
    return d[this.field] == 1 ? tpl_checked : tpl_no_checked;
};

//启用|禁用 不能修改
var layui_table_swith_tpl_44 = function (d) {
    var tpl_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="启用|禁用" checked type="checkbox" lay-skin="switch" disabled>';
    var tpl_no_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="启用|禁用" type="checkbox" lay-skin="switch" disabled>';
    return d[this.field] == 1 ? tpl_checked : tpl_no_checked;
};

//冻结|正常
var layui_table_swith_tpl_5 = function (d) {
    var tpl_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="正常|冻结" checked type="checkbox" lay-skin="switch">';
    var tpl_no_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="正常|冻结" type="checkbox" lay-skin="switch">';
    return d[this.field] == 1 ? tpl_checked : tpl_no_checked;
};
//不可申请|可申请
var layui_table_swith_tpl_55 = function (d) {
    var tpl_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="可申请|不可申请" checked type="checkbox"  disabled="disabled" lay-skin="switch">';
    var tpl_no_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="可申请|不可申请" type="checkbox" disabled="disabled" lay-skin="switch">';
    var tpl_owned = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="已有|已有" type="checkbox" disabled="disabled" lay-skin="switch">';
    if(d[this.field] == 3){
        return '已有';
    }else if(d[this.field] == 1){
        return '可申请';
    }else {
        return '不可申请';
    }

};
//待审核|通过|不通过
var layui_table_swith_tpl_53 = function (d) {
    if(d[this.field] == 3){
        return '<span style="color: green">审核通过</span>';
    }else if(d[this.field] == 1){
        return '待审核';
    }else {
        return '<span style="color: red">拒绝</span>';
    }

};
//会员名
var layui_table_user_tpl_1 = function (d) {
    var tpl_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="开启|冻结" checked type="checkbox" lay-skin="switch">';
    var tpl_no_checked = '<input name="' + this.field + '" lay-filter="' + this.field + '" value="1" data-json="' + encodeURIComponent(JSON.stringify(d)) + '" lay-text="开启|冻结" type="checkbox" lay-skin="switch">';
    return d[this.field] == 1 ? tpl_checked : tpl_no_checked;
};

//层级
var layui_table_user_level_tpl_1 = function (d) {
    if (d.lid_lock == 1) {
        return "<font color='red'>" + d[this.field] + "</font>";
    } else {
        return d[this.field];
    }

};
//金钱
var layui_table_money_1 = function (d) {
    if (is_null(d[this.field]) || d[this.field] == '') {
        return d[this.field];
    }
    try {
        var new_val = parseFloat(d[this.field]);
        if (new_val < 0) {
            new_val = "<font color='red'>" + new_val + "</font>";
        }
        return new_val;
    } catch (e) {
        return d[this.field];
    }
};

//金钱带百分号
var layui_table_money_rate_1 = function (d) {
    if (is_null(d[this.field]) || d[this.field] == '') {
        return '0%';
    }
    try {
        var new_val = parseFloat(d[this.field]);
        if (new_val < 0) {
            new_val = "<font color='red'>" + new_val + "%</font>";
        }else{
            new_val = new_val + '%';
        }
        return new_val;
    } catch (e) {
        return d[this.field];
    }
};

//图片显示
var layui_table_pic_1 = function (d) {
    var tpl_img = '<a href="#" onclick=\'show_one_pic("'
        + d[this.field] +
        '");\'><img style="display: inline-block; width: 50%; height: 100%;" src="'
        + d[this.field] +
        '"></a>';
    return tpl_img;
};

//json展示
var layui_table_json_1 = function (d) {
    var obj = eval('(' + d[this.field] + ')');
    return JSON.stringify(obj);
};

//时间戳格式化模板1
var layui_table_time_tpl_1 = function (d) {
    //console.log(d);
    return unixtime2str(d[this.field]).substring(2);
    ;
};

//时间戳格式化模板2
var layui_table_time_tpl_2 = function (d) {
    //console.log(d);
    return unixtime2str(d[this.field]);
};

//时间戳格式化模板3
var layui_table_time_tpl_3 = function (d) {
    //console.log(d);
    return unixtime2str_date(d[this.field]);
};

var layui_table_user_tpl_1 = function (d) {
    var username = d[this.field];
    layer.tips('Hi，我是tips', this, {
        tips: 1
    });
    return str;
};

//合并2个json
function merge_json(json1, json2) {
    var count1 = Object.keys(json1).length;
    var count2 = Object.keys(json2).length;
    if (count1 == 0 && count2 == 0) {
        return {};
    } else if (count1 > 0 && count2 == 0) {
        return json1;
    } else if (count1 == 0 && count2 > 0) {
        return json2;
    } else {
        return eval('(' + (JSON.stringify(json1) + JSON.stringify(json2)).replace(/}{/, ',') + ')');
    }
}


/**
 * 表单搜索
 * @param main_table 加载的table
 * @param search_form_id  搜索的表单 id，当id为空是，查询空条件
 * @param extend_search_parm   扩展查询条件，extend_search_parm 用 json传参，类如：{id:1}
 * @param page 查询起始页
 */
function reload_table_data(main_table, search_form_id, extend_search_parm, page, search_url) {
    layui.use(['table'], function () {
        var table = layui.table;


        //查询条件
        var post_data = form_data_to_json(search_form_id);

        if (!is_null(extend_search_parm) && is_json(extend_search_parm)) {
            post_data = merge_json(post_data, extend_search_parm);
        }

        var order_by = {};
        try {
            if (is_json(post_data.sort)) {
                order_by = post_data.sort;
            } else {
                try {
                    order_by = {
                        'sort': main_table.config.initSort.field
                        , 'order': main_table.config.initSort.type
                    };
                } catch (e) {
                    console.log(e);
                }
            }
        } catch (e) {
            console.log(e);
        }

        var o = {};

        try {
            if (is_json(order_by)) {
                o['initSort'] = {field: order_by.sort, type: order_by.order};
                post_data['sort'] = order_by.sort;
                post_data['order'] = order_by.order;
            }
        } catch (e) {
            console.log(e);
        }

        o['where'] = post_data;
        if (!is_null(page)) {
            //重新从第 N 页开始
            o['page'] = {
                curr: parseInt(page)
            };
        }
        if (!is_null(search_url)) {
            o['url'] = search_url;
        }
        console.log('reload_table_data param:');
        console.log(o);
        table.reload(main_table.config.id, o);
    });
}

/**
 * 表单搜索
 * @param main_table_id 加载的table
 * @param search_form_id  搜索的表单 id，当id为空是，查询空条件
 */
function do_search_table(main_table, search_form_id, extend_search_parm, search_url) {
    reload_table_data(main_table, search_form_id, extend_search_parm, 1, search_url);
}

/*
播放声音
 */

var play_mp3_howl;

function play_mp3(mp3_url, is_loop) {
    try {
        play_mp3_howl.stop();
    } catch (e) {

    }
    try {
        if (is_null(is_loop)) {
            is_loop = false;
        }
        play_mp3_howl = new Howl({
            src: mp3_url,
            //volume: 0.5,
            loop: is_loop
        });
        play_mp3_howl.play();
    } catch (e) {
        console.log(e);
    }
}

function form_date(is_default_set_today) {
    console.log(is_default_set_today);
    if (is_default_set_today == undefined) {
        is_default_set_today = true;
    }
    layui.use(['layer', 'laydate'], function () {

        //========================================== layui引用区 ==========================================
        var $ = layui.$
            , laydate = layui.laydate
        ;

        //开始日期
        var insStart = laydate.render({
            elem: '#search_start_date'
            , type: 'date'
            , format: 'yyyy-MM-dd'
            //, min: 0
            , done: function (value, date) {
                //更新结束日期的最小日期
                insEnd.config.min = lay.extend({}, date, {
                    month: date.month - 1
                });
                //自动弹出结束日期的选择器
                insEnd.config.elem[0].focus();
            }
        });

        //结束日期
        var insEnd = laydate.render({
            elem: '#search_end_date'
            , type: 'date'
            , format: 'yyyy-MM-dd'
            //, min: 0
            , done: function (value, date) {
                //更新开始日期的最大日期
                insStart.config.max = lay.extend({}, date, {
                    month: date.month - 1
                });
            }
        });

        //默认设置今天
        if (is_default_set_today) {
            form_do_set_day(1, null, null);
        }
    });
}

function parse_float(val) {
    if (!is_null(val)) {
        try {
            val = parseFloat(val);
        } catch (e) {
            val = val;
        }
    }
    return val;
}

function convert_all_children_text_to_float(seletor) {
    $ = layui.$;
    var r = /^(-?\d+)(\.\d+)?$/　　//浮点型
    var all_element = $(seletor).find("*");
    //console.log(all_element);
    all_element.each(function () {
        var val = $(this).text();
        if (r.test(val)) {
            var new_val = parseFloat(val);
            if (new_val < 0) {
                new_val = "<font color='red'>" + new_val + "</font>";
            }
            $(this).html(new_val);
        }
    });
}

function layui_table_summary(res, layui_table_class_id) {
    $ = layui.$;
    if (is_null(layui_table_class_id)) {
        layui_table_class_id = ".layui-table-box";
    }
    if (res.summary) {
        if ($(".layui-table-footer-summary").length > 0) {
            $(".layui-table-footer-summary").html(res.summary)
        } else {
            $(layui_table_class_id).append(
                '<div class="layui-table-footer-summary">' + res.summary + '</div>'
            );
        }
    }
}
/*
 * 字符串操作类，主要用于字符串的添加和删除。例如：在字符串 "a,b,c"中添加字符串"d",或者直接删除某个字符串。
 * 主要提供将给定字符串添加到某个字符串，中间用逗号分隔
 */
var StringOperate = {
    separator: ",", //字符串分隔符
    baforeInsert: false, //字符串追加方式，默认false是在后面添加，true在追加到前面
    isRepeat: false, //追加的字符串是否可重复添加
    isDeleteAll: true, //删除所有匹配的字符串

    //左边添加分隔符
    lInsertSeparator: function (operateString) {
        if (operateString.indexOf(this.separator) == 0)
            return operateString;
        return this.separator + operateString;
    },
    //右边添加分隔符
    rInsertSeparator: function (operateString) {
        if (operateString.lastIndexOf(this.separator) == (operateString.length - this.separator.length))
            return operateString;
        return operateString + this.separator;
    },
    //去除左边分隔符
    lSeparatorTrim: function (operateString) {
        if (operateString.indexOf(this.separator) == 0)
            return operateString.substring(1);
        return operateString;
    },
    //去除右边的分隔符
    rSeparatorTrim: function (operateString) {
        if (operateString.lastIndexOf(this.separator) == (operateString.length - this.separator.length))
            return operateString.substring(0, operateString.length - 1);
        return operateString;
    },
    //追加字符串，将str字符串 追加到operateString中
    add: function (operateString, str) {
        if (str && str != "") {
            if (this.isRepeat) {//重复追加
                if (this.baforeInsert) {//追加在开头
                    return this.rSeparatorTrim(this.lSeparatorTrim(str + this.separator + operateString));
                }
                return this.rSeparatorTrim(this.lSeparatorTrim(operateString + this.separator + str));
            } else {
                //开头和结尾都添加分隔符
                operateString = this.lInsertSeparator(this.rInsertSeparator(operateString));
                if (operateString.indexOf(this.separator + str + this.separator) == -1) {
                    if (this.baforeInsert) {
                        return this.rSeparatorTrim(this.lSeparatorTrim(str + operateString));
                    } else {
                        return this.rSeparatorTrim(this.lSeparatorTrim(operateString + str));
                    }
                }
                return this.rSeparatorTrim(this.lSeparatorTrim(operateString));
            }
        }
    },
    //删除指定字符串
    remove: function (operateString, str) {
        if (operateString && str && operateString != "" && str != "") {
            //开头和结尾都添加分隔符
            operateString = this.lInsertSeparator(this.rInsertSeparator(operateString));
            if (this.isDeleteAll) {
                operateString = operateString.replace(new RegExp(this.separator, "g"), this.separator + this.separator);
                //删除所有匹配的字符串
                operateString = operateString.replace(new RegExp(this.separator + str + this.separator, "g"), this.separator);
                operateString = operateString.replace(new RegExp(this.separator + "{2,}", "g"), this.separator);
            } else {
                operateString = operateString.replace(new RegExp(this.separator + str + this.separator), this.separator);
            }
            return this.rSeparatorTrim(this.lSeparatorTrim(operateString));
        }
    }
};